package cn.edu.jou.controller;

import cn.edu.jou.common.R;
import cn.edu.jou.dto.DishDto;
import cn.edu.jou.entity.Category;
import cn.edu.jou.entity.Dish;
import cn.edu.jou.entity.DishFlavor;
import cn.edu.jou.service.CategoryService;
import cn.edu.jou.service.DishFlavorService;
import cn.edu.jou.service.DishService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());

        dishService.saveWithFlavor(dishDto);

        return R.success("新增菜品成功");
    }

    /**
     * 菜品信息分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    //page:页码，pageSize:页面显示数量，name:前端传回来的查询条件
    public R<Page> page(int page, int pageSize, String name) {
        //构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        //构造条件构造器
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //根据name进行查询，添加过滤条件
        lambdaQueryWrapper.like(name!=null,Dish::getName,name);

        //添加排序条件
        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);

        //执行分页查询
        dishService.page(pageInfo,lambdaQueryWrapper);

        //DishDtoPage中没有值，要通过拷贝的方式来将pageInfo中的值拷贝到DishDtoPage中
        //对象拷贝,但是要忽略掉Page中的records，因为该records对应的是list集合中的数据
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list =
                records.stream().map((item)->{
                    DishDto dishDto = new DishDto();
                    BeanUtils.copyProperties(item,dishDto);
                    Long categoryId = item.getCategoryId();//分类ID
                    //根据id来查询菜品名称
                    Category category = categoryService.getById(categoryId);
                    if (category != null) {
                        String categoryName = category.getName();
                        dishDto.setCategoryName(categoryName);
                    }
                    return dishDto;
                }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {

        DishDto dishDto = dishService.getByIdWithFlavor(id);

        return R.success(dishDto);
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());

        dishService.updateWithFlavor(dishDto);

        return R.success("修改菜品成功");
    }
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable int status,@RequestParam List<Long> ids){
        log.info(String.valueOf(status));
        Dish dish = new Dish();
        dish.setStatus(status);
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //queryWrapper.eq(Dish::getId,ids);
        queryWrapper.in(Dish::getId,ids);
        dishService.update(dish,queryWrapper);
            /*LambdaUpdateWrapper<Dish> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(Dish::getId,ids).set(Dish::getStatus,status);
            dishService.update(wrapper);*/
        return R.success("修改成功");

    }


    /**
     * 根据条件来查询对应的菜品数据
     * @param dish
     * @return
     */
        /*@GetMapping("/list")
        public R<List<Dish>> list(Dish dish){

            //构造查询条件对象
            LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<Dish>();
            queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
            queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getCreateTime);
            List<Dish> list = dishService.list(queryWrapper);
            return R.success(list);
        }*/
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        //将菜品数据缓存到Redis中
        List<DishDto> dishDtoList = null;

        //动态获取key
        String key = "dish_"+dish.getCategoryId()+"_"+dish.getStatus();

        //先从Redis中获取缓存数据
        dishDtoList= (List<DishDto>) redisTemplate.opsForValue().get(key);

        //是否获取到数据
        if (dishDtoList!=null) {
            //获取到数据，直接返回
            return R.success(dishDtoList);
        }
        //没有查询到，进入下一步，去查询数据库

        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null ,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus,1);

        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        //将查询到的数据存入redis中
        redisTemplate.opsForValue().set(key,dishDtoList,1, TimeUnit.HOURS);

        return R.success(dishDtoList);
    }

    /**
     * 删除数据
     * @param ids
     * @return
     */
    @DeleteMapping()
    public R<String> delete(@RequestParam List<Long> ids){
        //在删除数据前，先将口味表中绑定该dish_id的数据删除
        log.info("传过来的ids：{}",ids);
            /*LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId,ids);
            dishFlavorService.remove(queryWrapper);
            //删除dish表中数据
            dishService.removeById(ids);*/
            /*
            1.将传过来的id进行遍历，通过遍历来删除传过来的每个id所绑定的菜品口味
            2.将所有id绑定的口味删除完成后，删除这些菜品
             */
        if (ids!=null){
            for (Long id:
                    ids) {
                LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(DishFlavor::getDishId,id);
                dishFlavorService.remove(queryWrapper);
            }
            dishService.removeByIds(ids);
            return R.success("删除成功");
        }
        return R.error("删除失败");
    }
}
